package example.mybatis;

import java.io.IOException;
import java.io.Reader;

import javax.sql.DataSource;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

public class MyBatisExample {
	
	private SqlSessionFactory getSqlSessionFactory() throws IOException{
		String resource = "example/mybatis/mybatis-config.xml";
		Reader reader = Resources.getResourceAsReader(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
		return sqlSessionFactory;
	}
	
	private SqlSessionFactory getSqlSessionFactory2(){
		DataSource dataSource = null;
		TransactionFactory transactionFactory = new JdbcTransactionFactory();
		Environment environment = new Environment("development", transactionFactory, dataSource);
		Configuration configuration = new Configuration(environment);
		configuration.addMapper(Member.class);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
		return sqlSessionFactory;
	}
	
	public void test() throws IOException{
		SqlSessionFactory sqlSessionFactory = this.getSqlSessionFactory();
		SqlSession session = sqlSessionFactory.openSession();
		Member member = (Member) session.selectOne("example.mybatis.MemberMapper.selectMember", 200L);
		
		System.out.println(member);
		
		MemberMapper2 mapper = session.getMapper(MemberMapper2.class);
		member = mapper.selectMember2(200L);
		
		System.out.println(member);
		
		session.close();
	}

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		new MyBatisExample().test();
	}

}
